package com.xyxe.domain.strategy.service.Raffle;


import com.xyxe.domain.strategy.model.valobj.RuleTreeVO;
import com.xyxe.domain.strategy.model.valobj.StrategyAwardRuleModelVO;
import com.xyxe.domain.strategy.model.valobj.StrategyAwardStockKeyVO;
import com.xyxe.domain.strategy.repository.IStrategyRepository;
import com.xyxe.domain.strategy.service.AbstractRaffleStrategy;
import com.xyxe.domain.strategy.service.armory.IStrategyDispatch;
import com.xyxe.domain.strategy.service.rule.chain.ILogicChain;
import com.xyxe.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import com.xyxe.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;



/**
 *
 */
@Slf4j
@Service
public class DefaultRaffleStrategy extends AbstractRaffleStrategy {

    @Resource
    protected DefaultChainFactory chainFactory;
    @Resource
    protected DefaultTreeFactory treeFactory;
    public DefaultRaffleStrategy(IStrategyRepository repository, IStrategyDispatch strategyDispatch) {
        super(repository, strategyDispatch);
    }

    @Override
    public DefaultChainFactory.StrategyAwardVO raffleLogicChain(String userId, Long strategyId) {
        ILogicChain logicChain = chainFactory.openLogicChain(strategyId);
        return logicChain.logic(userId, strategyId);
    }

    @Override
    public DefaultTreeFactory.StrategyAwardVO raffleLogicTree(String userId, Long strategyId, Integer awardId) {
        StrategyAwardRuleModelVO strategyAwardRuleModel = repository.queryStrategyAwardRuleModel(strategyId, awardId);
        if (null == strategyAwardRuleModel)
            return DefaultTreeFactory.StrategyAwardVO.builder()
                    .awardId(awardId).build();
        RuleTreeVO ruleTreeVO = repository.queryRuleTreeVOByTreeId(strategyAwardRuleModel.getRuleModels());
        if (null == ruleTreeVO)
            throw new RuntimeException("存在抽奖策略的规则配置模型 key，未在库表中rule_tree、rule_tree_node、rule_tree_line配置对应的规则树信息");
        return treeFactory.openLogicTree(ruleTreeVO).process(userId, strategyId, awardId);
    }

    @Override
    public StrategyAwardStockKeyVO takeQueueValue() throws InterruptedException {
        return repository.takeQueueValue();
    }

    @Override
    public void updateStrategyAwardStock(Long strategyId, Integer awardId) {
        repository.updateStrategyAwardStock(strategyId, awardId);
    }
}
